package jnpf.service.impl;

import cn.hutool.core.util.IdUtil;
import jnpf.base.ActionResult;
import jnpf.base.service.impl.BillRuleServiceImpl;
import jnpf.model.themeLog.Themeupdatelog;
import jnpf.service.IThemeupdatelogService;
import jnpf.entity.*;
import jnpf.model.entity.EntityUpTheme;
import jnpf.model.thememange.excel.ExcelImportObj;
import jnpf.model.znm.theme.tree.TreeDragDTO;
import jnpf.model.znm.theme.tree.TreeVO;
import jnpf.permission.service.UserService;
import jnpf.service.*;
import jnpf.util.RandomUtil;
import jnpf.util.StringUtil;
import jnpf.util.UserProvider;
import jnpf.util.ZmnUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ZmnServiceImpl implements ZmnService {
    @Autowired
    ThemeMangeServiceImpl themeMangeService;
    @Autowired
    IThemeupdatelogService iThemeupdatelogService;
    @Autowired
    UserProvider userProvider;
    @Autowired
    private ThemeStructureVersionService themeStructureVersionService;
    @Autowired
    private TemplateService templateService;
    @Autowired
    private TemplateCategoryService templateCategoryService;
    @Autowired
    private TemplateAttributeService templateAttributeService;
    @Autowired
    private EntityService entityService;
    @Autowired
    private EntityCategoryService entityCategoryService;
    @Autowired
    private EntityAttributeService entityAttributeService;
    @Autowired
    private TagService tagService;
    @Autowired
    private EntityUpLogService entityUpLogService;
    @Autowired
    private BillRuleServiceImpl billRuleService;
    @Autowired
    private ThemeTreeService themeTreeService;

    @Autowired
    private ThemeService themeService;


    @Override
    public List<TreeVO> getThemeTree() {
        List<ThemeMangeEntity> list = themeMangeService.list();
        List<TreeVO> treeDTOList = new ArrayList<>();
        Map<String, TreeVO> dtoMap = new HashMap<>();

        for (ThemeMangeEntity entity : list) {
            TreeVO dto = new TreeVO();
            dto.setId(entity.getId());
            dto.setLabel(entity.getThemeName());
            dto.setParentId(entity.getPid());
            dto.setSort(entity.getSort());
            dto.setChildren(new ArrayList<>());
            dtoMap.put(entity.getId(), dto);
        }

        // 构建树结构
        for (TreeVO dto : dtoMap.values()) {
            String parentId = dto.getParentId();
            if (parentId == null || !dtoMap.containsKey(parentId)) {
                treeDTOList.add(dto);
            } else {
                TreeVO parent = dtoMap.get(parentId);
                parent.getChildren().add(dto);
            }
        }

        // 对每个节点的子节点进行排序
        for (TreeVO dto : dtoMap.values()) {
            if (dto.getChildren() != null && !dto.getChildren().isEmpty()) {
                dto.getChildren().sort((a, b) -> {
                    if (a.getSort() == null) return 1;
                    if (b.getSort() == null) return -1;
                    return a.getSort().compareTo(b.getSort());
                });
            }
        }

        // 添加层级编号
        addLevelNumbers(treeDTOList, "");

        return treeDTOList;
    }

    private void addLevelNumbers(List<TreeVO> nodes, String parentNumber) {
        for (int i = 0; i < nodes.size(); i++) {
            TreeVO node = nodes.get(i);
            String currentNumber = parentNumber.isEmpty() ? String.valueOf(i + 1) : parentNumber + "." + (i + 1);
            node.setLabel(currentNumber + " " + node.getLabel());
            if (node.getChildren() != null && !node.getChildren().isEmpty()) {
                addLevelNumbers(node.getChildren(), currentNumber);
            }
        }
    }


    @Override
    @Transactional
    public ActionResult<String> updateTreePosition(@Valid List<TreeDragDTO> dragDatum) {
        for (TreeDragDTO dragData : dragDatum) {
            ThemeTreeEntity current = themeTreeService.getById(dragData.getId());
            if (current == null) {
                return ActionResult.fail("未找到当前节点");
            }

            // 根据targetId查询目标节点（实时获取最新父节点）
            ThemeTreeEntity targetNode = themeTreeService.getById(dragData.getTargetId());
            if (targetNode == null) {
                return ActionResult.fail("未找到目标节点");
            }
            String realParentId = targetNode.getPid(); // 目标节点的当前父节点ID

            if ("inner".equals(dragData.getPosition())) {
                current.setPid(dragData.getTargetId());
                // 查询目标节点的现有子节点（按sort升序）
                List<ThemeTreeEntity> children = themeTreeService.lambdaQuery()
                        .eq(ThemeTreeEntity::getPid, dragData.getTargetId())
                        .orderByAsc(ThemeTreeEntity::getSort)
                        .list();

                if (children.isEmpty()) {
                    // 初始值改为 BigDecimal(1)
                    current.setSort(BigDecimal.ONE);
                } else {
                    // 取最小sort（BigDecimal）减1，使用BigDecimal运算
                    BigDecimal minSort = children.get(0).getSort();
                    current.setSort(minSort.subtract(BigDecimal.ONE));
                }
            } else {
                current.setPid(realParentId); // 使用目标节点的当前父节点ID
                List<ThemeTreeEntity> siblings = themeTreeService.lambdaQuery()
                        .eq(ThemeTreeEntity::getPid, realParentId) // 基于实时父节点查询兄弟节点
                        .orderByAsc(ThemeTreeEntity::getSort)
                        .list();

                Optional<ThemeTreeEntity> targetOpt = siblings.stream()
                        .filter(node -> node.getId().equals(dragData.getTargetId()))
                        .findFirst();

                if (!targetOpt.isPresent()) {
                    return ActionResult.fail("未找到目标节点");
                }
                ThemeTreeEntity targetNodeInSiblings = targetOpt.get();
                int targetIndex = siblings.indexOf(targetNodeInSiblings);

                if ("before".equals(dragData.getPosition())) {
                    if (targetIndex == 0) {
                        // 目标节点是第一个，新sort = 目标sort - 1（BigDecimal运算）
                        current.setSort(targetNodeInSiblings.getSort().subtract(BigDecimal.ONE));
                    } else {
                        // 取前一个节点和目标节点的平均值（保留2位小数）
                        BigDecimal prevSort = siblings.get(targetIndex - 1).getSort();
                        current.setSort(prevSort.add(targetNodeInSiblings.getSort())
                                .divide(BigDecimal.valueOf(2), 2, RoundingMode.HALF_UP));
                    }
                } else if("after".equals(dragData.getPosition())) { // "after"
                    if (targetIndex == siblings.size() - 1) {
                        // 目标节点是最后一个，新sort = 目标sort + 1（BigDecimal运算）
                        current.setSort(targetNodeInSiblings.getSort().add(BigDecimal.ONE));
                    } else {
                        // 取目标节点和后一个节点的平均值（保留2位小数）
                        BigDecimal nextSort = siblings.get(targetIndex + 1).getSort();
                        current.setSort(targetNodeInSiblings.getSort().add(nextSort)
                                .divide(BigDecimal.valueOf(2), 2, RoundingMode.HALF_UP));
                    }
                }
            }

            boolean success = themeTreeService.updateById(current);
            if (success && dragData.getThemeupdatelog() != null) {
                boolean logSaved = insertTreeUpdateLog(dragData.getThemeupdatelog(), dragData.getThemeId(), dragData.getId());
                if (!logSaved) {
                    return ActionResult.fail("节点拖拽日志录入异常");
                }
            }
        }
        return ActionResult.success();
    }

    public boolean insertTreeUpdateLog(Themeupdatelog dragData, String themeId, String nodeId) {
        if (themeId == null) {
            return false;
        } else {
            Integer num = 1;
            List<Themeupdatelog> themeid1 = iThemeupdatelogService.query().eq("themeId", themeId).list();
            if (themeid1 != null) {
                if (!themeid1.isEmpty()) {
                    num = themeid1.size() + 1;
                }
            }
            dragData.setCreateTime(new Date());
            dragData.setCreateUserId(userProvider.get().getUserId());
            dragData.setUpdatenumber(num);
            dragData.setNodeId(nodeId);
            dragData.setThemeId(themeId);
            return iThemeupdatelogService.save(dragData);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ActionResult importExcelTemplate(MultipartFile file, String nodeId) {
        try (Workbook workbook = new XSSFWorkbook(file.getInputStream())) {
            Sheet sheet = workbook.getSheetAt(0);

            // 检查表头是否适应新格式
            Row headerRow = sheet.getRow(0);
            if (headerRow == null || !"节点名称".equals(getCellValueAsString(headerRow.getCell(0))) || !"父节点名称".equals(getCellValueAsString(headerRow.getCell(1))) || !"描述".equals(getCellValueAsString(headerRow.getCell(2)))) {
                return ActionResult.fail("请使用正确的导入表格模板【节点名称,父节点名称,描述】");
            }

            // 存储父子关系映射
            Map<String, String> parentChildMap = new HashMap<>();
            // 存储所有实体
            Map<String, ExcelImportObj> allEntities = new LinkedHashMap<>();
            // 检查重复节点名称
            Set<String> themeNames = new HashSet<>();

            // 第一遍：收集所有节点并验证数据
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                int line = i + 1;
                if (row == null) continue;

                // 节点名称验证
                String themeName = getCellValueAsString(row.getCell(0));

                if (StringUtil.isEmpty(themeName)) {
                    return ActionResult.fail(String.format("第%d行错误：节点名称为空", line));
                }

                if (themeName.length() > 50) {
                    return ActionResult.fail(String.format("第%d行错误：节点名称【%s】长度超过50字符", line, themeName));
                }

                // 检查Excel中是否有重复节点名称
                if (!themeNames.add(themeName)) {
                    return ActionResult.fail(String.format("第%d行错误：节点名称【%s】在表格中重复", line, themeName));
                }

                // 检查数据库中是否已存在相同节点名称
                boolean exists = themeMangeService.lambdaQuery().eq(ThemeMangeEntity::getThemeName, themeName).exists();
                if (exists) {
                    return ActionResult.fail(String.format("第%d行错误：节点名称【%s】在数据库中已存在", line, themeName));
                }

                // 描述验证
                String description = getCellValueAsString(row.getCell(2));
                if (description.length() > 500) {
                    return ActionResult.fail(String.format("第%d行错误：描述【%s】长度超过500字符", line, description));
                }

                // 父节点名称
                String parentThemeName = getCellValueAsString(row.getCell(1));

                // 创建实体
                ExcelImportObj excelImportObj = new ExcelImportObj();
                excelImportObj.setThemeName(themeName);
                excelImportObj.setParentThemeName(parentThemeName);
                excelImportObj.setDescription(description);

                String id = UUID.randomUUID().toString();
                excelImportObj.setId("new_" + (new Date().getTime() + i));


                // 记录父子关系
                parentChildMap.put(themeName, parentThemeName);
                allEntities.put(themeName, excelImportObj);
            }

            // 构建层级关系
            for (Map.Entry<String, ExcelImportObj> entry : allEntities.entrySet()) {
                String themeName = entry.getKey();
                ExcelImportObj entity = entry.getValue();
                String parentThemeName = parentChildMap.get(themeName);
                if (StringUtil.isNotEmpty(parentThemeName)) {
                    ExcelImportObj parentEntity = allEntities.get(parentThemeName);
                    if (parentEntity != null) {
                        entity.setPid(parentEntity.getId());
                    }
                } else {
                    // 若父节点名称为空，则将 pid 设置为 nodeId
                    entity.setPid(nodeId);
                }
            }

            // 设置每层的sort字段
            Map<String, List<ExcelImportObj>> parentChildrenMap = new HashMap<>();
            for (ExcelImportObj entity : allEntities.values()) {
                String parentId = entity.getPid();
                parentChildrenMap.computeIfAbsent(parentId, k -> new ArrayList<>()).add(entity);
            }

            for (List<ExcelImportObj> children : parentChildrenMap.values()) {
                Collections.sort(children, Comparator.comparing(ExcelImportObj::getThemeName));
                for (int i = 0; i < children.size(); i++) {
                    children.get(i).setSort(i + 1);
                }
            }

            // 转为插入列表
            List<ExcelImportObj> excelList = new ArrayList<>(allEntities.values());
            List<ThemeTreeEntity> batchInsertList = new ArrayList<>();
            for (ExcelImportObj excelImportObj : excelList) {
                ThemeTreeEntity entity = new ThemeTreeEntity();
                entity.setName(excelImportObj.getThemeName());
                entity.setDes(excelImportObj.getDescription());
                entity.setId(excelImportObj.getId());
                entity.setPid(excelImportObj.getPid());
                entity.setSort(BigDecimal.valueOf(excelImportObj.getSort()));
                batchInsertList.add(entity);
            }

            // 将 ThemeTreeEntity 列表转换为 TreeVO 列表
            Map<String, TreeVO> treeVOMap = new HashMap<>();
            List<TreeVO> treeVOs = new ArrayList<>();

            // 先创建所有的 TreeVO 对象
            for (ThemeTreeEntity entity : batchInsertList) {
                TreeVO treeVO = new TreeVO();
                treeVO.setId(entity.getId());
                treeVO.setLabel(entity.getName());
                treeVO.setParentId(entity.getPid());
                treeVO.setSort(entity.getSort());
                treeVO.setDes(entity.getDes());
                treeVO.setStatus("1");
                treeVO.setChildren(new ArrayList<>());
                treeVOMap.put(entity.getId(), treeVO);
            }

            // 构建树结构
            for (TreeVO treeVO : treeVOMap.values()) {
                String parentId = treeVO.getParentId();
                if (parentId == null || !treeVOMap.containsKey(parentId)) {
                    treeVOs.add(treeVO);
                } else {
                    TreeVO parent = treeVOMap.get(parentId);
                    parent.getChildren().add(treeVO);
                }
            }

            // 对每个节点的子节点进行排序
            for (TreeVO treeVO : treeVOMap.values()) {
                if (treeVO.getChildren() != null && !treeVO.getChildren().isEmpty()) {
                    treeVO.getChildren().sort(Comparator.comparing(TreeVO::getSort));
                }
            }

            // 添加层级编号
//            addLevelNumbers(treeVOs, "");

            return ActionResult.success(treeVOs);
        } catch (IOException e) {
            return ActionResult.fail("导入异常：" + e.getMessage());
        }
    }


    private void collectNodes(List<ThemeTreeEntity> nodes, List<ThemeTreeEntity> result) {
        for (ThemeTreeEntity node : nodes) {
            result.add(node);
            if (node.getChildren() != null && !node.getChildren().isEmpty()) {
                collectNodes(node.getChildren(), result);
            }
        }
    }

    @Override
    public ActionResult saveThemeVersion(String themeId) {
        List<TreeVO> themeTree = themeService.getThemeTree(themeId, "0",true);
        if (themeTree.isEmpty()) {
            return ActionResult.fail("当前主题无层级");
        }

        // 获取当前日期部分
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String datePart = dateFormat.format(new Date());

        // 查询最新版本号
        ThemeStructureVersionEntity latestVersion = themeStructureVersionService.lambdaQuery().eq(ThemeStructureVersionEntity::getThemeId, themeId).orderByDesc(ThemeStructureVersionEntity::getVersion).last("LIMIT 1").one();

        // 创建新版本实体
        ThemeStructureVersionEntity newVersion = new ThemeStructureVersionEntity();
        newVersion.setAfterJson(ZmnUtil.convertThemeTreeToJson(themeTree));

        // 设置版本号为YYYYMMDD_序号格式
        int sequenceNumber = 1;
        if (latestVersion != null && latestVersion.getVersion() != null) {
            String[] parts = latestVersion.getVersion().split("_");
            if (parts.length == 2 && parts[0].equals(datePart)) {
                sequenceNumber = Integer.parseInt(parts[1]) + 1;
            }
        }
        newVersion.setVersion(datePart + "_" + sequenceNumber);

        newVersion.setCreatetime(new Date());
        newVersion.setCreateuserid(userProvider.get().getUserId());
        newVersion.setThemeId(themeId);

        // 保存新版本
        boolean success = themeStructureVersionService.save(newVersion);
        return success ? ActionResult.success("版本保存成功") : ActionResult.fail("版本保存失败");
    }


    @Override
    public ActionResult<List<ThemeStructureVersionEntity>> getThemeVersionInfo() {
        List<ThemeStructureVersionEntity> versions = themeStructureVersionService.lambdaQuery().select(ThemeStructureVersionEntity::getId, ThemeStructureVersionEntity::getVersion).orderByDesc(ThemeStructureVersionEntity::getCreatetime).list();

        return ActionResult.success(versions);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ActionResult<String> createEntity(@NotEmpty String templateId, Integer count) {
        // 通过模板 ID 获取模板信息
        TemplateEntity info = templateService.getInfo(templateId);
        if (info == null) {
            return ActionResult.fail("模板不存在");
        }

        try {
            // 查询模板分类
            List<TemplateCategoryEntity> templateCategories = templateCategoryService.lambdaQuery().eq(TemplateCategoryEntity::getTemplateId, templateId).list();

            // 存储创建的实体 ID 列表
            List<String> entityIds = new ArrayList<>();

            // 补充的参数
            String userId = userProvider.get().getUserId();
            Date crreateTime = new Date();

            // 存储待保存的实体主表数据列表
            List<EntityEntity> entityList = new ArrayList<>();
            // 存储待保存的实体分类数据列表
            List<EntityCategoryEntity> entityCategoryList = new ArrayList<>();
            // 存储待保存的实体属性数据列表
            List<EntityAttributeEntity> entityAttributeList = new ArrayList<>();

            // 循环创建指定数量的实体
            for (int i = 0; i < count; i++) {
                // 创建实体主表数据
                EntityEntity entity = new EntityEntity();
                entity.setDataLevel(1);
                entity.setTemplateId(info.getId());
                entity.setBelongUserId(userId);
                //流水号
                String doEntityFLow = billRuleService.getBillNumber("doEntityFLow", false);
                // 复制模板主表的相关属性到实体主表
                entity.setName(info.getName()); // 假设模板和实体主表都有 name 属性
                entity.setNumber(doEntityFLow);
                // 补充参数
                entity.setCreateUserId(userId);
                entity.setCreateTime(crreateTime);
                entity.setId(RandomUtil.uuId());

                entityList.add(entity);
                entityIds.add(entity.getId());

                // 处理实体分类和属性
                for (TemplateCategoryEntity templateCategory : templateCategories) {
                    String categoryId = RandomUtil.uuId();
                    // 创建实体分类数据
                    EntityCategoryEntity entityCategory = new EntityCategoryEntity();
                    // 复制模板分类的相关属性到实体分类
                    entityCategory.setCategory(templateCategory.getCategory());
                    entityCategory.setEntityId(entity.getId());
                    // 补充参数
                    entityCategory.setCreateUserId(userId);
                    entityCategory.setCreateTime(crreateTime);
                    entityCategory.setId(categoryId);

                    entityCategoryList.add(entityCategory);

                    // 查询模板分类下的属性this
                    List<TemplateAttributeEntity> templateAttributes = templateAttributeService.lambdaQuery().eq(TemplateAttributeEntity::getCategoryId, templateCategory.getId()).list();

                    // 处理实体分类下的属性
                    for (TemplateAttributeEntity templateAttribute : templateAttributes) {
                        // 创建实体属性数据
                        EntityAttributeEntity entityAttribute = new EntityAttributeEntity();
                        // 复制模板属性的相关属性到实体属性
                        entityAttribute.setAttrName(templateAttribute.getAttrName());
                        entityAttribute.setEntityId(entity.getId());
                        // 补充参数
                        entityAttribute.setCategoryId(categoryId);
                        entityAttribute.setAttrType(templateAttribute.getAttrType());
                        entityAttribute.setCreateUserId(userId);
                        entityAttribute.setCreateTime(crreateTime);
                        entityAttribute.setId(RandomUtil.uuId());
                        entityAttribute.setAttrSelectValue(templateAttribute.getAttrSelectValue());

                        entityAttributeList.add(entityAttribute);
                    }
                }
            }

            // 批量保存实体主表数据
            entityService.saveBatch(entityList);
            // 批量保存实体分类数据
            entityCategoryService.saveBatch(entityCategoryList);
            // 批量保存实体属性数据
            entityAttributeService.saveBatch(entityAttributeList);

            return ActionResult.success("实体创建成功");
        } catch (Exception e) {
            return ActionResult.fail("实体创建失败: " + e.getMessage());
        }
    }

    @Override
    public ActionResult<String> entityUpTheme(EntityUpTheme entityUpTheme) {
        String themeId = entityUpTheme.getThemeId();
        ThemeMangeEntity info = themeMangeService.getInfo(themeId);
        if (info == null) {
            return ActionResult.fail("主题不存在");
        }
        List<String> entityIdList = entityUpTheme.getEntityIdList();
        for (String entityId : entityIdList) {
            EntityEntity entity = entityService.getInfo(entityId);
            if (entity == null) {
                return ActionResult.fail("实体不存在");
            }
            entity.setThemeId(themeId);
            entityService.updateById(entity);

            // 记录挂载日志
            EntityUpLogEntity log = new EntityUpLogEntity();
            log.setId(RandomUtil.uuId());
            log.setEntityId(entityId);
            log.setThemeId(themeId);
            log.setCreateTime(new Date());
            log.setCreateUserId(userProvider.get().getUserId());
            entityUpLogService.save(log);
        }
        return ActionResult.success();
    }

    @Override
    public ActionResult<List<Map<String, String>>> getLabelListByType(String labelType) {
        // 根据标签类型查询标签列表
        List<TagEntity> tagList = tagService.lambdaQuery().eq(TagEntity::getTagType, labelType).list();
        List<Map<String, String>> result = new ArrayList<>();
        for (TagEntity tag : tagList) {
            Map<String, String> tagMap = new HashMap<>();
            tagMap.put("id", tag.getId());
            tagMap.put("name", tag.getName());
            result.add(tagMap);
        }
        return ActionResult.success(result);
    }

    @Override
    public ActionResult<List<TemplateEntity>> getTemplateVersionList(String templateId) {
        // 1. 先查询当前模板信息
        TemplateEntity currentTemplate = templateService.getInfo(templateId);
        if (currentTemplate == null) {
            return ActionResult.fail("模板不存在");
        }

        // 2. 获取该模板的第一个版本ID
        String firstUpdateId = currentTemplate.getFirstUpdateId();
        if (StringUtil.isEmpty(firstUpdateId)) {
            firstUpdateId = templateId;
        }

        // 3. 查询所有版本模板(包括当前模板)
        List<TemplateEntity> versionList = templateService.lambdaQuery().eq(TemplateEntity::getFirstUpdateId, firstUpdateId).or().eq(TemplateEntity::getId, firstUpdateId).orderByDesc(TemplateEntity::getVersion).list();

        return ActionResult.success(versionList);
    }

    @Override
    @Transactional
    public ActionResult<String> setMainTemplate(String templateId) {
        // 1. 获取当前模板信息
        TemplateEntity template = templateService.getById(templateId);
        if (template == null) {
            return ActionResult.fail("模板不存在");
        }

        // 2. 获取该模板的第一个版本ID
        String firstUpdateId = template.getFirstUpdateId();
        if (StringUtil.isEmpty(firstUpdateId)) {
            firstUpdateId = templateId;
        }

        // 3. 将所有同源模板的isMain设为2(非主版本)
        templateService.lambdaUpdate().eq(TemplateEntity::getFirstUpdateId, firstUpdateId).set(TemplateEntity::getIsMain, "2").update();

        // 4. 将当前模板设为1(主版本)
        template.setIsMain("1");
        templateService.updateById(template);

        return ActionResult.success("设置主版本成功");
    }

    @Override
    public ActionResult<List<ThemeStructureVersionEntity>> getThemeVersion(List<String> themeIds) {
        if (themeIds == null || themeIds.isEmpty()) {
            return ActionResult.fail("主题ID列表不能为空");
        }

        List<ThemeStructureVersionEntity> versions = themeStructureVersionService.lambdaQuery().in(ThemeStructureVersionEntity::getId, themeIds).list();

        // 转换为DTO列表
        List<ThemeStructureVersionEntity> result = new ArrayList<>();

        for (ThemeStructureVersionEntity version : versions) {
            if (version.getAfterJson() != null) {
                List<TreeVO> treeList = ZmnUtil.convertJsonToThemeTree(version.getAfterJson());
                // 复制一份 treeList，避免修改原数据
                List<TreeVO> numberedTreeList = new ArrayList<>(treeList);
                // 添加层级编号
                addLevelNumbers(numberedTreeList, "");
                // 构建带编号的字符串
                StringBuilder numberedString = new StringBuilder();
                buildNumberedString(numberedTreeList, numberedString);
                version.setAfterJson(numberedString.toString());
                result.add(version);
            }
        }

        return ActionResult.success(result);
    }

    private void buildNumberedString(List<TreeVO> nodes, StringBuilder builder) {
        for (TreeVO node : nodes) {
            builder.append(node.getLabel()).append("\n");
            if (node.getChildren() != null && !node.getChildren().isEmpty()) {
                buildNumberedString(node.getChildren(), builder);
            }
        }
    }


    private String getCellValueAsString(org.apache.poi.ss.usermodel.Cell cell) {
        if (cell == null) {
            return "";
        }
        // 根据单元格类型获取对应的值
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
                    // 处理日期类型
                    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
                    return sdf.format(cell.getDateCellValue());
                } else {
                    // 处理数字类型
                    double numericValue = cell.getNumericCellValue();
                    // 检查是否为整数
                    if (numericValue == (long) numericValue) {
                        return String.valueOf((long) numericValue);
                    } else {
                        return String.valueOf(numericValue);
                    }
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                // 计算公式结果
                org.apache.poi.ss.usermodel.FormulaEvaluator evaluator = cell.getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator();
                return getCellValueAsString(evaluator.evaluateInCell(cell));
            default:
                return "";
        }
    }

}
